/* 
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.appspot.dispotrains;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Pair;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.Toast;

import com.appspot.dispotrains.station.Line;
import com.appspot.dispotrains.station.Station;
import com.appspot.dispotrains.station.StationAdapter;
import com.appspot.dispotrains.station.StationLister;

import java.util.HashMap;

public class GareListFragment extends ExpandableListFragment implements
    LoaderManager.LoaderCallbacks<Pair<HashMap<Integer, Line>, HashMap<Integer, Station>>> {

  private static final String STATE_ACTIVATED_POSITION = "activated_position";

  private Callbacks mCallbacks = sDummyCallbacks;
  private int mActivatedPosition = ListView.INVALID_POSITION;
  private HashMap<Integer, Station> mData;

  public interface Callbacks {
    public void onItemSelected(int id);
  }

  private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(int id) {};
  };

  public GareListFragment() {}

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
      setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState != null && savedInstanceState.containsKey("data")) {
      mData = (HashMap<Integer, Station>) savedInstanceState.getSerializable("data");
    }

    if (mData == null) {
      getLoaderManager().initLoader(0, null, this);
    }
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (!(activity instanceof Callbacks)) {
      throw new IllegalStateException("Activity must implement fragment's callbacks.");
    }

    mCallbacks = (Callbacks) activity;
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mCallbacks = sDummyCallbacks;
  }

  @Override
  public void onListItemClick(ListView listView, View view, int position, long id) {
    super.onListItemClick(listView, view, position, id);
    // mCallbacks.onItemSelected(listView.);
  }

  @Override
  public boolean onChildClick(
      ExpandableListView listView, View view, int groupPosition, int childPosition, long id) {
    mCallbacks.onItemSelected((int) id);
    return true;
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mActivatedPosition != ListView.INVALID_POSITION) {
      outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
    }
    if (mData != null) {
      outState.putSerializable("data", mData);
    }
  }

  public void setActivateOnItemClick(boolean activateOnItemClick) {
    getExpandableListView().setChoiceMode(
        activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE);
  }

  public void setActivatedPosition(int position) {
    if (position == ListView.INVALID_POSITION) {
      getExpandableListView().setItemChecked(mActivatedPosition, false);
    } else {
      getExpandableListView().setItemChecked(position, true);
    }

    mActivatedPosition = position;
  }

  /**
   * @see android.app.LoaderManager.LoaderCallbacks#onCreateLoader(int,
   *      android.os.Bundle)
   */
  @Override
  public Loader<Pair<HashMap<Integer, Line>, HashMap<Integer, Station>>> onCreateLoader(
      int id, Bundle args) {
    return new StationLister(getActivity());
  }

  /**
   * @see android.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.content.Loader,
   *      java.lang.Object)
   */
  @Override
  public void onLoadFinished(Loader<Pair<HashMap<Integer, Line>, HashMap<Integer, Station>>> loader,
      Pair<HashMap<Integer, Line>, HashMap<Integer, Station>> data) {
    if (data == null || data.second == null) {
      CharSequence text = "Impossible de se connecter. Vérifiez votre connection et recommencez.";
      int duration = Toast.LENGTH_LONG;

      Toast toast = Toast.makeText(getActivity(), text, duration);
      toast.show();
      return;
    }

    setListAdapter(new StationAdapter(getActivity(), data.second));
    onContentChanged();

    if (isResumed()) {
      setListShown(true);
    } else {
      setListShownNoAnimation(true);
    }

  }

  /**
   * @see android.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.content.Loader)
   */
  @Override
  public void onLoaderReset(
      Loader<Pair<HashMap<Integer, Line>, HashMap<Integer, Station>>> loader) {
    // TODO: find what needs to go here.
  }
}
